package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动!");
        ExecutorService service = Executors.newCachedThreadPool();
        while (true) {
            //通过accept方法,把内核中已经建立好的连接拿到应用程序中
            Socket clientSocket = serverSocket.accept();
           /* Thread t = new Thread(() -> {
                processConnection(clientSocket);
            });
            t.start();
*/
            //更好一点的方式是使用线程池
            service.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }

    //通过这个方法,处理当前的连接
    public void processConnection(Socket clientSocket) {
        //先打印日志,表示已经有客户端连接上了
        System.out.printf("[%s: %d] 客户端上线!\n", clientSocket.getInetAddress(), clientSocket.getPort());

        //接下来进行数据交互
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            //使用try( )是为了避免使用完字节流忘记关闭
            while (true) {
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()) {
                    System.out.printf("[%s: %d] 客户端下线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                //1.读取数据并分析
                String request = scanner.next();
                //2.根据请求,计算响应
                String response = process(request);
                //3.把响应写回到客户端
                //可以把String转换成字节数组写到OutputStream
                //也可以用Print Writer包裹
                PrintWriter printWriter = new PrintWriter(outputStream);
                //此处的println不是打印到控制台了,而是写入到outputStream的流对象中,也就是写到clientSocket 里面
                printWriter.println(response);
                //刷新缓冲区,如果没有刷新操作,数据可能还在内存中,没有被写入网卡
                printWriter.flush();
                //4.打印一下这次请求交互的内容
                System.out.printf("[%s: %d] req = %s, resp = %s \n", clientSocket.getInetAddress(), clientSocket.getPort(),
                        request, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9089);
        server.start();
    }
}
